<template>
  <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-change="getFile"
      :limit="1"
      list-type="picture-card"
      :auto-upload="false"
      @click="test"
  >
    <el-image
        style="width: 100%; height: 100%"
        v-if="imageUrl" :src="imageUrl"
    ></el-image>
    <el-icon v-if="!imageUrl">
      <plus/>
    </el-icon>
    <template #tip>
      <div class="el-upload__tip">
        请上传图片类型的文件
      </div>
    </template>
  </el-upload>
</template>

<script>
import {ElMessage} from "element-plus";

export default {
  name: "UserLoadPhoto",
  data() {
    return {
      imageUrl: ''
    }
  },
  methods: {
    test() {
      console.log('...dwwdq')
    },
    getFile(file) {
      this.uploadTest(file)
      console.log('test')
      this.getBase64(file.raw).then(res => {
        this.imageUrl = res
        console.log(res)
      })
    },
    uploadTest(file) {
      if (file.size / (1024 * 1024) > 15) {
        ElMessage({
          type: 'warning',
          message: '文件大小不能超过15MB!'
        })
      }
      let suffix = this.getFileType(file.name)
      let suffixArray = ["jpg", "png", "jpeg", "gif"]
      if (suffixArray.indexOf(suffix) === -1) {
        ElMessage({
          type: 'warning',
          message: '请上传jpg,jpeg,png类型图片!'
        })
      }
    },
    getFileType(name) {

      let startIndex = name.lastIndexOf(".")
      if (startIndex !== -1) {
        return name.slice(startIndex + 1).toLowerCase()
      } else {
        return ""
      }
    },
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
          imgResult = reader.result
        }
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    }
  }
}
</script>

<style scoped>

</style>